import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { SFSchema, SFUISchema } from '@delon/form';
import { itcoreService } from '@shared/itcore/services/itcore.service';
@Component({
    selector: 'app-itcore-connection',
    template: `
       <div>
       <button nz-button nzType="default" (click)='currentOperateStatus=1'><i nz-icon nzType="plus-circle" nzTheme="outline"></i>新增数据库连接</button>
       <button nz-button type="button"  (click)="refresh();">刷新</button>
       <div class='collect-list' *ngIf='currentOperateStatus===0'>
        <div  *ngFor="let item of collectionList; let idx = index" class="collect-item">
            <div class="collect-item-d" >
                <img class='collect-img' [src]='findDatabaseIcon(item.DataBaseType)' width='32px' />
                <span  class='collect-title'>{{item.Title}}</span>
                <p *ngIf='item.Remark' >{{item.Remark}}</p>
                
            </div>
            <span  class='collect-actions'>
                <i nz-icon nzType="star" title='选择该连接' (click)='check(item)' nzTheme="outline"></i>
                <i nz-icon nzType="edit" title='编辑' (click)='edit(item)'  nzTheme="outline"></i>
                <i nz-icon nzType="delete"  title='删除' nzTheme="outline" nz-popconfirm nzPopconfirmTitle="你确定要删除?" nzOkText="确定" nzCancelText="取消" (nzOnConfirm)="delete(item)" ></i>
            </span>
        </div>

      
       </div>
        <div class='add-module' *ngIf='currentOperateStatus!=0'>
        <sf #sf mode="edit" [schema]="schema" [ui]="ui" [formData]="formData" [button]="null">
                <div class="">
                <button nz-button type="button" (click)="sf.reset();currentOperateStatus=0">关闭</button>

                <button nz-button type="button" [nzType]="'primary'" (click)="testCollection(sf)" [disabled]="!sf.valid" >
                    测试连接
                </button>

                <button nz-button type="submit" [nzType]="'primary'" (click)="submitCollection(sf)" [disabled]="!sf.valid" >
                    保存
                </button>
                </div>
            </sf>
        </div>
  </div>
  `,
    styles: [
        `.add-module{
               padding: 3%;
        }
        .collect-list{
            padding:10px;
            display:flex;
            flex-wrap:wrap;
            justify-content: space-around;
        }
        .collect-item{
            box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
            margin-top: 10px;
            cursor: pointer;
            position:relative;
        }
        
        .collect-item:hover.collect-item:before{
            opacity: 1;
        }
        .collect-item:hover .collect-actions{
            opacity: 1;
        }
        .collect-item:before{
            position: absolute;
            z-index: 1;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,.35);
            opacity: 0;
            transition: all .3s;
            content: " ";
        }
        .collect-item-d{
            padding: 10px 20px;
        }
        .collect-item p{
            margin:0;
            color: #e6b37d;
        }
        .collect-title{
            padding-left:10px
        }
        .collect-actions{
            position: absolute;
            top: 50%;
            left: 50%;
            z-index: 10;
            white-space: nowrap;
            transform: translate(-50%,-50%);
            opacity: 0;
            transition: all .3s;
            color:#fff;
            font-size:20px;
        }
        .collect-actions i{
            padding-right:10px;
        }
        `
    ]
})
export class ItcoreConnectionComponent {
    constructor(private itcore: itcoreService, private cdf: ChangeDetectorRef) {
        this.getCollectList();
    }

    // 传出的成功回调
    @Output() checkSuccess = new EventEmitter<any>();

    // 列 接口配置
    @Input() connectOption: any;
    // 值
    @Input() value: any;

    // 操作状态 1：列表，2：新增，3：编辑
    currentOperateStatus = 0;

    // 数据库类型
    dataBaseType = [
        { id: 0, text: 'SqlServer', isOpen: true },
        { id: 1, text: 'Sqlite' },
        { id: 2, text: 'MySql', isOpen: true },
        { id: 3, text: 'PostgreSql' },
        { id: 4, text: 'Oracle' },
    ];
    // 连接字符串集合
    collectionList: any[];
    // sf schema
    schema: SFSchema = {
        properties: {
            Title: {
                type: 'string',
                title: '标题',
            },
            DataBaseType: {
                type: 'number',
                title: '数据库类型',
                enum: this.dataBaseType.filter(x => x.isOpen).map(item => {
                    return { value: item.id, label: item.text };
                })
            },
            ConnectString: {
                type: 'string',
                title: '连接字符串',
            },
            Remark: {
                type: 'string',
                title: '备注',
            }
        },
        required: ['Title', 'DataBaseType', 'ConnectString']
    };
    // sf ui
    ui: SFUISchema = {
        '*': { spanLabelFixed: 100, grid: { span: 18 } },
        $DataBaseType: { widget: 'select', },
    };
    formData = {};
    currentCheckData = {};
    // 提交
    submitCollection(sf) {
        this.itcore.http.post(`api/Db/DbConnectPool/${this.currentOperateStatus === 1 ? 'Create' : 'update'}`, [sf.value]).subscribe(res => {
            if (res.Type === 200) {
                this.itcore.msgSrv.success('操作成功');
                this.currentOperateStatus = 0;
                sf.reset();
                this.getCollectList();
            } else {
                this.itcore.msgSrv.error('操作失败！');
            }
        });
    }
    testCollection(sf) {
        const param = { Type: sf.value.DataBaseType, ConnectString: sf.value.ConnectString };
        this.itcore.http.post('api/Db/Db/TestCollect', param).subscribe(res => {
            if (res.Type === 200) {
                this.itcore.msgSrv.success('连接成功~');
            } else {
                this.itcore.msgSrv.error('连接失败,请检查连接字符串！');
            }
        });
    }
    getCollectList() {
        this.itcore.http.post('api/Db/DbConnectPool/Read').subscribe(res => {
            this.collectionList = res.Data;
            this.cdf.detectChanges();
            if (this.value) {
                const currentValue = this.collectionList.find(x => x.Id === this.value);
                this.checkSuccess.emit({ DataBaseType: currentValue.DataBaseType, Id: currentValue.Id, Title: currentValue.Title });
            }
        });
    }
    delete(item) {
        this.itcore.http.post('api/Db/DbConnectPool/Delete', [item.Id]).subscribe(res => {
            if (res.Type === 200) {
                this.itcore.msgSrv.success('删除成功！');
                this.collectionList = this.collectionList.filter(x => x.Id !== item.Id);
                this.cdf.detectChanges();
                // this.getCollectList();
            } else {
                this.itcore.msgSrv.error('删除失败：' + res.Message);
            }
        });
    }
    findDatabaseIcon(type: number) {
        if (type === 0) {
            return 'assets/itcore/sqlserver.svg';
        }
        if (type === 2) {
            return 'assets/itcore/mysql.svg';
        }

        return '';
    }
    check(item) {
        this.checkSuccess.emit({ DataBaseType: item.DataBaseType, Id: item.Id, Title: item.Title });
    }
    // 编辑
    edit(item) {
        this.currentOperateStatus = 3;
        this.formData = item;
    }
    // 刷新
    refresh() {
        this.getCollectList();
    }
}
